#!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
Dialog node and layer for kytten dialogs
Created on 23 jul 2011

@author: Devon Scott-Tunkin
@author: Joakim Lindskog (minor modifications)

Copyright (c) 2009, Devon Scott-Tunkin
Copyright (c) 2011 Joakim Lindskog
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <copyright holder> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Thanks to Richard Jones for his original editor and tile library
and Conrad Wong for the "kytten" gui library

Cocograph tile map editor for cocos2d
'''
import pyglet, cocos
from cocos.director import director
from cocos import layer

class DialogNode(cocos.batch.BatchableNode):
    def __init__(self, dialog=None):
        super(DialogNode, self).__init__()
        self.dialog = dialog

    def set_batch(self, batch, group=None, z=0):
        super(DialogNode, self).set_batch(batch, group)
        if self.dialog is not None:
            self.dialog.batch = self.batch
            self.dialog.group = self.group

    def delete(self):
        '''
        Deletes this DialogNode
        '''
        self.dialog.teardown()
        super(DialogNode, self).on_exit()
        self.parent.remove(self)

    def draw(self):
        pass
        
        
class DialogLayer(layer.Layer):
    '''
    A layer for DialogNodes
    '''
    is_event_handler = True
    def __init__(self, dialog=None):
        super(DialogLayer, self).__init__()
        self.batchnode = cocos.batch.BatchNode()
        self.add(self.batchnode)
        director.interpreter_locals["director"].window.register_event_type('on_update')        
        self.schedule(self.update)
        self.exited = False
        
    def update(self, dt):
        '''
        Updates this layer
        
        @param dt: time elapsed since last update, in seconds
        @type dt: float
        '''
        director.interpreter_locals["director"].window.dispatch_event('on_update', dt)

    def add_dialog(self, dialog_node):
        '''
        Adds a dialog node to this layer
        
        @param dialog_node: the dialog node to add
        @type dialog_node: DialogNode
        '''
        if dialog_node is not None:
            self.batchnode.add(dialog_node)
        
    def on_key_press(self, symbol, modifiers):
        if self.exited: return False
        for c in self.batchnode.get_children():
            if c.dialog.focus and hasattr(c.dialog.focus, 'on_key_press'):
                if symbol not in [pyglet.window.key.COLON, pyglet.window.key.RETURN]:
                    c.dialog.focus.on_key_press(symbol, modifiers)
                elif symbol == pyglet.window.key.RETURN:
                    c.dialog.on_key_press(symbol, modifiers)
                return True 

    def on_key_release(self, symbol, modifiers):
        if self.exited: return False
        for c in self.batchnode.get_children():
            if c.dialog.on_key_release(symbol, modifiers):
                return True

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        if self.exited: return False
        for c in self.batchnode.get_children():
            if c.dialog.on_mouse_drag(x, y, dx, dy, buttons, modifiers) \
            or c.dialog.focus != None:
                return True 

    def on_mouse_motion(self, x, y, dx, dy):
        if self.exited: return False
        for c in self.batchnode.get_children():
            c.dialog.on_mouse_motion(x, y, dx, dy)
            if c.dialog.hover is not None:
                return True
            #~ else:
                #~ c.dialog.set_focus(None)

    def on_mouse_press(self, x, y, button, modifiers):
        #print "exited "+str(self.exited)+" self "+str(self)
        if self.exited: return False
        was_handled = False
        for c in self.batchnode.get_children():
            if c.dialog.on_mouse_press(x, y, button, modifiers):
                was_handled = True
            else:
                c.dialog.set_wheel_hint(None)
                c.dialog.set_wheel_target(None)
        return was_handled

    def on_mouse_release(self, x, y, button, modifiers):
        if self.exited: return False
        was_handled = False
        for c in self.batchnode.get_children():
            if c.dialog.on_mouse_release(x, y, button, modifiers):
                was_handled = True  
        return was_handled

    def on_mouse_scroll(self, x, y, scroll_x, scroll_y):
        if self.exited: return False
        for c in self.batchnode.get_children():
            if c.dialog.on_mouse_scroll(x, y, scroll_x, scroll_y):
                return True

    def on_text(self, text):
        if self.exited: return False
        for c in self.batchnode.get_children():
            if c.dialog.focus and hasattr(c.dialog.focus, 'on_text'):
                if text.strip() != "":
                    c.dialog.focus.on_text(text)
                return True 

    def on_text_motion(self, motion):
        if self.exited: return False
        for c in self.batchnode.get_children():
            if c.dialog.focus and hasattr(c.dialog.focus, 
                                          'on_text_motion'):
                c.dialog.focus.on_text_motion(motion)
                return True

    def on_text_motion_select(self, motion):
        if self.exited: return False
        for c in self.batchnode.get_children():
            if c.dialog.focus and hasattr(c.dialog.focus, 
                                          'on_text_motion_select'):
                c.dialog.focus.on_text_motion_select(motion)
                return True

    def on_exit(self):
        super(DialogLayer, self).on_exit()
        self.exited = True
        self.unschedule(self.update)
        for c in self.batchnode.get_children():
            c.delete()